package com.yunxi.poc.starbucks.controller;


import com.yunxi.poc.starbucks.common.BaseController;
import com.yunxi.poc.starbucks.service.ITStoreCapacityAvgService;
import com.yunxi.poc.starbucks.util.CacheUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author shiyuan.xlc
 * @since 2021-09-06
 */
@Controller
@RequestMapping("/starbucks/store_capacity_avg")
public class TStoreCapacityAvgController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(TStoreCapacityAvgController.class);

    @Resource
    ThreadPoolTaskExecutor executorService;

    @Resource
    ITStoreCapacityAvgService storeCapacityAvgService;

    @ResponseBody
    @RequestMapping(value = {""}, method = RequestMethod.GET)
    public ResponseEntity batch() {
        // for (String storeId : BizConstant.TARGET_STORES) {
        for (String storeId : CacheUtil.storeIds) {
            executorService.execute(() -> {
                logger.info("Task running ->" + " storeId: " + storeId);
                storeCapacityAvgService.calulateCapacity(storeId,
                        LocalDate.of(2021, 4, 1),
                        LocalDate.of(2021, 5, 31),
                        Arrays.asList(
                                LocalDate.of(2021, 7, 13),
                                LocalDate.of(2021, 7, 22),
                                LocalDate.of(2021, 7, 30),
                                LocalDate.of(2021, 8, 14)
                        )
                );
                logger.info("Task done ->" + " storeId: " + storeId);

                logger.info("Task count: " + executorService.getThreadPoolExecutor().getTaskCount()
                        + " Task active count: " + (executorService.getActiveCount() - 1)
                        + " Task completed count: " + (executorService.getThreadPoolExecutor().getCompletedTaskCount() + 1)
                        + " Task ending at: " + LocalDateTime.now());
            });
        }

        logger.info("Task count: " + executorService.getThreadPoolExecutor().getTaskCount() + " Task start at: " + LocalDateTime.now());

        return ResponseEntity.status(HttpStatus.OK).body("1");
    }
}
